<template>
  <div class="address-container">
    <div class="address-header">
      <h2>地址管理</h2>
    </div>

    <el-table
      v-loading="loading"
      :data="paginatedAddressList"
      style="width: 100%"
      border
      max-height="600"
      :scrollbar-always-on="true"
    >
      <el-table-column prop="userId" label="用户ID" width="100" />
      <el-table-column label="地址列表" min-width="800">
        <template #default="{ row }">
          <el-table :data="row.addresses" border>
            <el-table-column prop="receiver_name" label="收货人" width="120" />
            <el-table-column prop="receiver_phone" label="联系电话" width="140" />
            <el-table-column prop="address" label="详细地址" min-width="300" />
            <el-table-column label="默认地址" width="100" align="center">
              <template #default="{ row: address }">
                <el-tag
                  :type="address.is_default ? 'success' : 'info'"
                  effect="plain"
                >
                  {{ address.is_default ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="180">
              <template #default="{ row: address }">
                {{ formatTime(address.created_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row: address }">
                
                <el-button
                  type="primary"
                  link
                  @click="handleEdit(address)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  link
                  @click="handleDelete(address)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllAddress, deleteAddress, updateAddress } from '../../api/address'
import { useAuthStore } from '../../stores/auth'

const router = useRouter()
const authStore = useAuthStore()
const loading = ref(false)
const addressList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 将地址按用户ID分组
const groupedAddressList = computed(() => {
  const groups = {}
  addressList.value.forEach(address => {
    if (!groups[address.userId]) {
      groups[address.userId] = {
        userId: address.userId,
        addresses: []
      }
    }
    groups[address.userId].addresses.push(address)
  })
  return Object.values(groups)
})

// 获取当前页的地址列表
const paginatedAddressList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return groupedAddressList.value.slice(start, end)
})

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 处理每页数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  try {
    const date = new Date(time)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-')
  } catch (e) {
    console.error("时间格式化错误:", e)
    return time
  }
}

// 获取地址列表
const fetchAddressList = async () => {
  try {
    loading.value = true
    const res = await getAllAddress()
    if (res.status === 0) {
      addressList.value = res.data
      // 更新总数
      total.value = groupedAddressList.value.length
      // 重置到第一页
      currentPage.value = 1
    } else {
      ElMessage.error(res.message || '获取地址列表失败')
    }
  } catch (error) {
    console.error('获取地址列表错误:', error)
    ElMessage.error('获取地址列表失败')
  } finally {
    loading.value = false
  }
}



// 编辑地址
const handleEdit = (address) => {
  router.push({
    name: 'AddressEdit',
    params: { id: address.id }
  })
}

// 删除地址
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这个地址吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteAddress(row.id)
      if (res.status === 0) {
        ElMessage.success('删除地址成功')
        // 重新获取地址列表
        await fetchAddressList()
      } else {
        ElMessage.error(res.message || '删除地址失败')
      }
    } catch (error) {
      console.error('删除地址错误:', error)
      ElMessage.error('删除地址失败')
    }
  }).catch(() => {})
}

onMounted(() => {
  fetchAddressList()
})

// 添加样式以优化嵌套表格的显示
const style = document.createElement('style')
style.textContent = `
.el-table__expanded-cell .el-table {
  margin: 0 !important;
}
.el-table .el-table__expanded-cell {
  padding: 10px !important;
}
`
document.head.appendChild(style)
</script>

<style scoped>
.address-container {
  padding: 20px;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.address-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.pagination-container {
  margin-top: 20px;
  padding: 10px 0;
  display: flex;
  justify-content: flex-end;
}
</style>